<template>
  <el-dialog
    v-model="editFormVisible"
    title="修改角色"
    :append-to-body="true"
    @close="closeDialog"
    destroy-on-close
  >
    <el-form
      class="editroleform"
      :model="editRoleForm"
      :rules="editFormRule"
      ref="roleform"
      label-width="100px"
    >
      <el-form-item label="角色名称" prop="name">
        <el-input ref="rolename" v-model="editRoleForm.name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="editRoleForm.isDefault" label="默认"></el-checkbox>
        <el-tooltip
          class="item"
          effect="dark"
          content="新用户默认拥有此角色"
          placement="top"
        >
          <i class="el-icon-info"></i>
        </el-tooltip>
      </el-form-item>
    </el-form>

    <div class="modal-footer">
      <el-button type="primary" @click="saveRole">保存</el-button>
    </div>
  </el-dialog>
</template>
<script setup lang="ts">
import { FormRules, FormInstance } from "element-plus";
import { getRole,updateRole} from "@/api/identity/role/index";
// import { addUser, addUserToOrganization } from "@/api/identity/user/index";
import { RoleForm, RoleItem, RoleItemUpdate } from "@/api/identity/role/types";
let editFormVisible = ref<boolean>(false);
const Props = defineProps({
  FormVisible: { type: Boolean, default: false },
  Id: { type: String, default: null },
});
const emit = defineEmits(["closedialogevent", "refresh"]);

editFormVisible.value = Props.FormVisible;
const roleform = ref<FormInstance>();
const editRoleForm = ref<RoleItemUpdate>({
  name: "",
  isDefault: false,
  isPublic: false,
  concurrencyStamp: "",
});

const editFormRule: FormRules = reactive({
  name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
});

async function pg_Init() {
  if (Props.Id != null) {
    await getRole(Props.Id)
      .then((res) => {
        
          editRoleForm.value.name = res.name;
          editRoleForm.value.isDefault = res.isDefault;
          editRoleForm.value.concurrencyStamp = res.concurrencyStamp;
       
      })
      .catch((error) => {
        ElNotification({
          title: "提示",
          message: error,
          type: "error",
          duration: 2000,
        });
      });
  }
}

function closeDialog() {
  editFormVisible.value = false;
  emit("closedialogevent", editFormVisible.value);
}

 function saveRole() {
  roleform.value?.validate(async (valid, fields) => {
    if (valid) {
       
     let res =  await updateRole(Props.Id,editRoleForm.value);
     if(res){
      ElNotification({
            title: '提示',
            message: '修改角色成功',
            type: "success",
            duration: 2000,
          });
          closeDialog();
          emit('refresh');
     }
    } else {
      console.log("error submit!", fields);
    }
  });
}

onMounted(() => {
  pg_Init();
})

watch(
  () => Props.FormVisible,
  (newValue) => {
    editFormVisible.value = Props.FormVisible;
  }
);

</script>
